package com.example.demo.service.impl;

import com.example.demo.dao.UserDao;
import com.example.demo.entity.UserBean;
import com.example.demo.service.UserService;
import com.example.demo.util.JwtUtil;
import com.example.demo.util.PageEntity;
import com.example.demo.util.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public List<UserBean> all() {
        return userDao.getAll();
    }

    @Override
    public Integer add(UserBean userBean) {
        return userDao.insert(userBean);
    }


    @Override
    public Integer update(UserBean userBean) {
        return userDao.edit(userBean);
    }

    @Override
    public Integer delete(Integer id) {
        return userDao.del(id);
    }

    @Override
    public UserBean one(Integer id) {
        return userDao.getOne(id);
    }

    @Override
    public PageEntity list(Integer pageNo, Integer pageSize,String address,String name,String sortOrder) {

        // 根据页码 求 跳过多少条数据
        Integer jump = (pageNo-1)*pageSize;

        Integer count = userDao.getCount(address, name);
        List<UserBean> rows = userDao.getPage(jump, pageSize, address, name, sortOrder);


        PageEntity<List> listPageEntity = new PageEntity<List>(rows,count);
        return listPageEntity;
    }

    @Override
    public ResponseEntity login(UserBean loginUser) {
        HashMap<String, String> data = new HashMap<>();
        UserBean user = userDao.getByName(loginUser.getName());

        System.out.println(loginUser);
        System.out.println(user);
        if(user!=null){
            String password = user.getPassword();
            if(password.equals(loginUser.getPassword())){
                // 账号 密码正确
                data.put("id",user.getId().toString());
                data.put("name",(String) user.getName());
                // 生产Token
                String token = JwtUtil.createToken(user);
                data.put("token",token);
                return new ResponseEntity(200,"登陆成功",data);

            }
        }
        return new ResponseEntity(500,"账号或密码不正确",null);
    }
}

